package com.muyu.kafka.producer;


import com.muyu.kafka.domain.AllData;
import com.muyu.kafka.domain.Data1;
import com.muyu.kafka.domain.Data2;
import com.muyu.kafka.domain.Data3;
import com.muyu.kafka.kafkaConfig.KafkaSendResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * @ClassName producter
 * @Description 描述
 * @Author LiuZeZhang
 * @Date 2024/04/11 14:10
 */
@Component
public class producter {
    @Autowired
    private KafkaTemplate<Object,Object> kafkaTemplate;

    public producter(KafkaTemplate<Object, Object> kafkaTemplate, KafkaSendResultHandler kafkaSendResultHandler) {
        this.kafkaTemplate = kafkaTemplate;
        kafkaTemplate.setProducerListener(kafkaSendResultHandler);
    }

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Value("${redis.name.key}")
    private String key;

    @Transactional
    @Scheduled(cron = "0/30 * * * * ?")
    public void send() {
        Data1 data1 = new Data1();
        //随机生成的数据
        Long id = generateRandomLong(10);
        String name = generateChineseName();
        String card = generateChineseID();
        int age = calculateAge(card);
        Date date = getDate();

        data1.setId(BigInteger.valueOf(id));
        data1.setXm(name);
        data1.setCard(card);
        data1.setAge(age);
        data1.setTime(date);
        kafkaTemplate.send("data1", UUID.randomUUID().toString(), data1);

        Data2 data2 = new Data2();
        data2.setId(BigInteger.valueOf(id));
        data2.setXm(name);
        data2.setCard(card);
        //把图片转换为base64json类型
        String images="D:\\摸底题\\1.png";
        data2.setPhoto1(getImagesbase64String(images));
        data2.setPhoto2(getImagesbase64String(images));
        kafkaTemplate.send("data2", UUID.randomUUID().toString(), data2);

        Data3 data3 = new Data3();
        data3.setId(BigInteger.valueOf(id));
        data3.setPlate(generateChineseLicensePlate());
        data3.setTime(date);

        kafkaTemplate.send("data3", UUID.randomUUID().toString(), data3);

        AllData dataAll = new AllData();
        dataAll.setId(BigInteger.valueOf(id));
        dataAll.setXm(name);
        dataAll.setCard(card);
        dataAll.setAge(age);
        dataAll.setTime(date);
        dataAll.setPlate(generateChineseLicensePlate());
        dataAll.setPhoto1(getImagesbase64String(images));
        dataAll.setPhoto2(getImagesbase64String(images));

        redisTemplate.opsForList().rightPushAll(key,dataAll.toString());
    }


    public static String generateChineseLicensePlate() {
        Random random = new Random();
        // 省份简称
        String[] provinceAbbreviations = {"京", "津", "沪", "渝", "冀", "豫", "云", "辽", "黑", "湘", "皖", "鲁", "新", "苏", "浙", "赣", "鄂", "桂", "甘", "晋", "蒙", "陕", "吉", "闽", "贵", "粤", "青", "藏", "琼", "宁"};
        // 生成省份简称
        String province = provinceAbbreviations[random.nextInt(provinceAbbreviations.length)];
        // 生成后面的数字和字母组合（假设车牌号中包含7位字符，其中最后一位是字母）
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            if (i < 2) { // 前两位是数字
                sb.append(random.nextInt(10));
            } else { // 后四位是大写字母
                sb.append((char) (random.nextInt(26) + 'A'));
            }
        }
        // 生成完整的车牌号码
        String licensePlate = province + sb.toString();
        return licensePlate;
    }

    public static Date getDate(){
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 定义日期时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化当前时间为字符串
        String formattedDateTime = now.format(formatter);
        System.out.println("格式化后的当前时间字符串：" + formattedDateTime);

        // 将格式化后的时间字符串解析为日期时间对象
        LocalDateTime parsedDateTime = LocalDateTime.parse(formattedDateTime, formatter);

        // 将解析后的 LocalDateTime 对象转换为 java.util.Date 对象
        Date date = java.sql.Timestamp.valueOf(parsedDateTime);

       return date;
    }

    //随机生成id
    public static Long generateRandomLong(int length) {
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder(length);
        // 生成随机Long类型数字的每一位
        for (int i = 0; i < length; i++) {
            // 生成0到9之间的随机数字
            stringBuilder.append(random.nextInt(10));
        }
        return Long.valueOf(stringBuilder.toString());
    }

    //随机生成姓名
    private static final String[] FIRST_NAMES = {"张", "王", "李", "赵", "刘", "陈", "杨", "黄", "周", "吴"};
    private static final String[] LAST_NAMES = {"伟", "芳", "娜", "秀英", "强", "磊", "洋", "艳", "勇", "军"};

    public static String generateChineseName() {
        Random random = new Random();
        String firstName = FIRST_NAMES[random.nextInt(FIRST_NAMES.length)];
        String lastName = LAST_NAMES[random.nextInt(LAST_NAMES.length)];
        return lastName + firstName;
    }

    public static int calculateAge(String idCard) {
        // 解析身份证号中的出生日期
        // 身份证号中出生日期的起始位置为第7位，结束位置为第14位
        String birthdayString = idCard.substring(6, 14);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date birthday = null;
        try {
            birthday = sdf.parse(birthdayString);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 计算年龄
        Calendar birthCalendar = Calendar.getInstance();
        birthCalendar.setTime(birthday);
        Calendar currentCalendar = Calendar.getInstance();
        int age = currentCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR);
        // 如果当前月份小于出生月份，或者当前月份等于出生月份但当前日期小于出生日期，则年龄减一
        if (currentCalendar.get(Calendar.MONTH) < birthCalendar.get(Calendar.MONTH) ||
                (currentCalendar.get(Calendar.MONTH) == birthCalendar.get(Calendar.MONTH) &&
                        currentCalendar.get(Calendar.DAY_OF_MONTH) < birthCalendar.get(Calendar.DAY_OF_MONTH))) {
            age--;
        }
        return age;
    }

    //随机生成身份证
    public static String generateChineseID() {
        Random random = new Random();
        // 随机生成地址码（前6位）
        StringBuilder addressCode = new StringBuilder();
        addressCode.append(String.format("%02d", random.nextInt(100)));
        addressCode.append(String.format("%02d", random.nextInt(100)));
        addressCode.append(String.format("%02d", random.nextInt(100)));

        // 随机生成出生日期码（中间8位，格式为YYYYMMDD）
        StringBuilder birthdayCode = new StringBuilder();
        birthdayCode.append(String.format("%04d", random.nextInt(100) + 1900));
        birthdayCode.append(String.format("%02d", random.nextInt(12) + 1));
        birthdayCode.append(String.format("%02d", random.nextInt(28) + 1));

        // 随机生成顺序码（最后4位）
        StringBuilder sequenceCode = new StringBuilder();
        sequenceCode.append(String.format("%03d", random.nextInt(1000)));

        // 组合身份证号码
        StringBuilder chineseID = new StringBuilder();
        chineseID.append(addressCode).append(birthdayCode).append(sequenceCode);

        // 计算校验码（最后一位）
        int[] coefficientArray = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] validationCodeArray = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += (chineseID.charAt(i) - '0') * coefficientArray[i];
        }
        chineseID.append(validationCodeArray[sum % 11]);

        return chineseID.toString();
    }


    private String getImagesbase64String(String images) {
        String baseImg = null;
        try {
            // 创建文件对象，根据提供的图片路径
            File file = new File(images);
            FileInputStream fileInputStream = new FileInputStream(file);

            // 根据文件长度创建字节数组，用于存储文件内容
            byte[] buffer = new byte[(int) file.length()];

            // 读取文件内容到字节数组
            fileInputStream.read(buffer);

            // 关闭文件输入流
            fileInputStream.close();

            // 将字节数组转换为Base64编码的字符串
            baseImg = Base64.getEncoder().encodeToString(buffer);
        } catch (Exception e) {
            // 如果过程中发生异常，抛出运行时异常
            throw new RuntimeException(e);
        }
        return baseImg;
    }



}
